package jers.util;

import java.io.File;
import java.net.URL;
import java.rmi.RMISecurityManager;

import jers.JERS;

/**
 * Classe utilitaria de resursos de seguranca.
 *  
 * @author 
 * 		<a href="mailto:felipe.zappala@gmail.com">
 * 			Luis Felipe Zappala
 * 		</a> [ <a href="http://lncc.br/ist">ISTCC-P</a> / 2009 ]
 */
public final class SecurityUtil {

	private SecurityUtil() {
		super();
	}
	
	/**
	 * Configura o arquivo de politicas de seguranca padrao no ambiente.<br />
	 * Configura a propriedade do sistema 'java.security.policy'
	 * com o arquivo de politicas de acesso do sistema 'jers.policy'.
	 */
	public static void setupSecurityPolicy() {
		try {
			URL policyFile;
			String javaPolicy = JERS.config.getProperty("java.security.policy"); 
			if ("jers.policy".equals(javaPolicy)) {
				// Carrega o arquivo padrao
				policyFile = JERS.class.getResource("/META-INF/jers.policy");
			} else {
				// Carrega o arquivo definido na configuracao
				policyFile = new File(javaPolicy).toURI().toURL();
			}
			String pathPolicyFile = policyFile.toString();
			System.setProperty("java.security.policy", pathPolicyFile);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Configura o gerenciador de seguranca do ambiente.
	 */
	public static void setupSecurityManager() {
		SecurityManager sm = System.getSecurityManager();
		if (sm == null) {
			sm = new RMISecurityManager();
			System.setSecurityManager(sm);
			JERS.log.info("[SecurityUtil] setupSecurityManager: ",
					"SecurityManager is setted as [",
					sm.getClass().getName(), "]");
		} else {
			JERS.log.error("[SecurityUtil] setupSecurityManager: ",
					"SecurityManager already is setted as [",
					sm.getClass().getName(), "]");
		}
	}
	
}
